package com.centaline.androidsalesblog.rx.database;

import com.centaline.androidsalesblog.model.businissobject.RongUserInfoBo;
import com.centaline.androidsalesblog.model.databaseobject.StaffDo;
import com.centaline.androidsalesblog.model.databaseobject.UserDo;
import com.centaline.androidsalesblog.utils.RongUserIdUtil;

import org.litepal.crud.DataSupport;

import java.util.List;
import java.util.Locale;

import rx.Observable;
import rx.Subscriber;

/**
 * 融云用户信息
 * Created by guilin on 16/3/18.
 */
final class RongUserInfoOnSubscribe implements Observable.OnSubscribe<RongUserInfoBo> {

    private final String targetId;

    public RongUserInfoOnSubscribe(String targetId) {
        this.targetId = targetId;
    }

    @Override
    public void call(Subscriber<? super RongUserInfoBo> subscriber) {
        if (targetId != null &&
                targetId.contains("_")) {
            String[] split = targetId.split("_");
            if (split.length == 2) {//登录用户
                UserDo userDo = DataSupport.findFirst(UserDo.class);
                if (userDo != null &&
                        !subscriber.isUnsubscribed()) {
                    subscriber.onNext(new RongUserInfoBo(RongUserIdUtil.getCustomerId(userDo.getUserId()),
                            userDo.getNickName(),
                            userDo.getUserPhotoUrl(),
                            userDo.getPhone()));
                }
            } else {//经纪人
                List<StaffDo> staffDos = DataSupport.where("staffNo = ?", split[2].toUpperCase(Locale.CHINA)).find(StaffDo.class);
                if (staffDos != null &&
                        staffDos.size() > 0 &&
                        !subscriber.isUnsubscribed()) {
                    StaffDo staffDo = staffDos.get(0);
                    subscriber.onNext(new RongUserInfoBo(RongUserIdUtil.getSatffId(staffDo.getStaffNo()),
                            staffDo.getCnName(),
                            staffDo.getImgUrl(),
                            staffDo.getMobile()));
                }
            }
            subscriber.onCompleted();
        }
    }
}
